package model

import (
	"gorm.io/gorm"
	__ "grpc/basic/proto"
)

type User struct {
	gorm.Model
	Phone    string `gorm:"type:char(11)" json:"phone"`
	Password string `gorm:"type:varchar(32)" json:"password"`
	Username string `gorm:"type:varchar(20)" json:"username"`
	Status   string `gorm:"type:varchar(20)" json:"status"`
}

func (u *User) Adduser(db *gorm.DB) error {
	return db.Debug().Create(&u).Error
}

func (u *User) VeryPhone(db *gorm.DB, phone string) error {
	return db.Debug().Where("phone =?", phone).First(&u).Error

}

func (u *User) VeryUser(db *gorm.DB, id int64) error {
	return db.Debug().Where("id =?", id).First(&u).Error

}

func (u *User) ListUser(db *gorm.DB, id, page, size int64) (list []*__.ListUser, err error) {
	if page <= 0 {
		page = 1
	}

	if size <= 0 || size >= 20 {
		size = 10
	}

	offset := (page - 1) * size
	err = db.Debug().Model(&User{}).
		Select("users.id as userId", "users.username as username", "videos.title as title",
			"videos.content as content", "videos.image as image", "videos.types as types", "ratings.fraction as fraction").
		Joins("left join ratings on ratings.user_id = users.id").
		Joins("left join videos on videos.user_id = users.id").
		Where("users.id =?", id).Offset(int(offset)).Limit(int(size)).
		Find(&list).Error
	return list, err
}
